package com.itfitness.opengldemo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.net.Uri;
import android.opengl.GLES20;
import android.opengl.GLException;
import android.opengl.GLSurfaceView;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Size;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.IntBuffer;
import java.util.Locale;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;


/**
 * @Description: java类作用描述
 * @Author: 作者名
 * @UpdateUser: 更新者：
 * @UpdateRemark: 更新说明：
 */
public class CameraView extends GLSurfaceView implements GLSurfaceView.Renderer {
    //gpu地址
    private int textures;
    private SurfaceTexture surfaceTexture;
    private CameraDrawer cameraDrawer;
    //拍照的相关变量
    public static Bitmap bmp;
    private boolean isTakePicture = false;
    public CameraView(Context context) {
        super(context);
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //设置OpenGL版本
        setEGLContextClientVersion(2);
        //设置GLSurfaceView监听
        setRenderer(this);
        //渲染方式: 手动 RENDERMODE_WHEN_DIRTY
        //         自动 RENDERMODE_CONTINUOUSLY
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        initCameraX();
    }

    private void initCameraX() {
        PreviewConfig config = new PreviewConfig.Builder()
//                .setTargetResolution(new Size(640,480))
                .setLensFacing(CameraX.LensFacing.BACK)
                .build();
        Preview preview = new Preview(config);
        CameraX.bindToLifecycle((LifecycleOwner) getContext(),preview);
        preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
            @Override
            public void onUpdated(Preview.PreviewOutput output) {
                //拿到输出画布
                surfaceTexture = output.getSurfaceTexture();
            }
        });
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        //拿到摄像头在GPU地址
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        surfaceTexture.attachToGLContext(textures);
        surfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
            @Override
            public void onFrameAvailable(SurfaceTexture surfaceTexture) {
                //摄像头回调
                //触发 onDrawFrame
                requestRender();
            }
        });
        cameraDrawer = new CameraDrawer();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(final GL10 gl) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        LogUtils.eTag("测试","触发成功");
        surfaceTexture.updateTexImage();
        cameraDrawer.draw(textures);
        // 获取GLSurfaceView的图片并保存
        if (isTakePicture) {
            isTakePicture = false;
            bmp = createBitmapFromGLSurface(0, 0, getWidth(),
                    getHeight(), gl);
            try {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ImageUtils.save2Album(bmp, Bitmap.CompressFormat.JPEG);
                        ToastUtils.showShort("保存成功");
                    }
                }).start();
            }catch (Exception e){}
        }
    }
    //拍照
    public void takePhoto(){
        isTakePicture = true;
    }
    // 将OpenGL渲染完的画面转为Bitmap
    private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl) {
        int bitmapBuffer[] = new int[w * h];
        int bitmapSource[] = new int[w * h];
        IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
        intBuffer.position(0);
        try {
            gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE,
                    intBuffer);
            int offset1, offset2;
            for (int i = 0; i < h; i++) {
                offset1 = i * w;
                offset2 = (h - i - 1) * w;
                for (int j = 0; j < w; j++) {
                    int texturePixel = bitmapBuffer[offset1 + j];
                    int blue = (texturePixel >> 16) & 0xff;
                    int red = (texturePixel << 16) & 0x00ff0000;
                    int pixel = (texturePixel & 0xff00ff00) | red | blue;
                    bitmapSource[offset2 + j] = pixel;
                }
            }
        } catch (GLException e) {
            return null;
        }
        return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
    }
}
